<template>
  <div class="ppm-box">
    <el-form
      :model="formData"
      ref="formDataRules"
      :rules="formDataRules"
      label-width="120px"
    >
      <el-row class="ppm-box-pad-top" type="flex" justify="space-between">
        <el-col :span="12">
          <h4 class="ppm-label">
            订单项信息
            <span class="ppm-text"
              >流水号:{{ formData["ORDER_ITEM-CUST_SO_NUMBER"].value }}</span
            >
            <span class="ppm-text"
              >产品名称:{{ formData["ORDER_ITEM-PRODUCT_NAME"].value }}</span
            >
          </h4>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请数量" prop="104324520.value">
            <el-input
              v-model.number="formData['104324520'].value"
              style="width: 60%"
              :disabled="formData['104324520'].disabled"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider class="ppm-divider"></el-divider>

      <el-row>
        <el-col :span="10">
          <el-form-item label="需求单类型" v-if="false">
            <dyn-btngroup
              v-model="formData['ORDER_ITEM-REQ_TYPE'].value"
              :productId="infors.productId"
              :attrId="formData['ORDER_ITEM-REQ_TYPE'].id"
              :formData="formData"
              :formKey="'ORDER_ITEM-REQ_TYPE'"
              :disableds="formData['ORDER_ITEM-REQ_TYPE'].disabled"
            />
          </el-form-item>
          <el-form-item label="要求完成时间" prop="ORDER_ITEM-ORDER_DATE.value">
            <el-col>
              <el-date-picker
                style="width: 100%"
                v-model="formData['ORDER_ITEM-ORDER_DATE'].value"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :editable="false"
                :picker-options="taxStartDate"
                :disabled="disabled"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="付费方式" required>
            <dyn-btngroup
              v-model="formData['PROD_INST-100010204'].value"
              :productId="infors.productId"
              :attrId="formData['PROD_INST-100010204'].id"
              @change="selectA"
              :formData="formData"
              :formKey="'PROD_INST-100010204'"
              :disableds="formData['PROD_INST-100010204'].disabled"
            />
          </el-form-item>
          <el-form-item
            label="集团付费账户"
            required
            style="margin-top: 30px"
            prop="TD_V_PROD_INST-100010097.value"
          >
            <!-- <input-grid
              v-model="formData['TD_V_PROD_INST-100010097'].text"
              sqlCode="findCust"
              @getrow="
                (val) => {
                  formData['TD_V_PROD_INST-100010097'].value = val;
                }
              "
            /> -->
            <input-dialog
              v-model="formData['TD_V_PROD_INST-100010097'].text"
              text="acctName"
              @getrow="getrowHandler2"
              @loadata="loadBusiManageOptions2"
              :config="busiManageConfig1"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form :model="fm" ref="fm" :rules="rules" label-width="120px">
            <el-form-item label="租用期限" prop="hireTime">
              <el-col :span="5">
                <el-input
                  v-model.number="hireTime"
                  @input="onHireTime"
                ></el-input>
              </el-col>
              <el-col :span="5">
                <el-select v-model="hireUnit" placeholder="请选择">
                  <el-option label="年" value="年" />
                  <el-option label="月" value="月" />
                  <el-option label="日" value="日" />
                </el-select>
              </el-col>
            </el-form-item>
          </el-form>
          <!-- <el-form-item label="优先级">
            <dyn-btngroup
              v-model="formData['ORDER_ITEM-PRIORITY'].value"
              :productId="infors.productId"
              :attrId="formData['ORDER_ITEM-PRIORITY'].id"
              :formData="formData"
              :formKey="'ORDER_ITEM-PRIORITY'"
              :disableds="formData['ORDER_ITEM-PRIORITY'].disabled"
            />
          </el-form-item> -->
          <el-form-item
            label="付费客户"
            v-show="formData['PROD_INST-100010204'].value == '30010001'"
          >
            <el-input
              v-model="formData['PROD_INST-100010096'].text"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="付费运营商"
            v-show="formData['PROD_INST-100010204'].value == '30010002'"
            prop="PROD_INST-100010096.value"
          >
            <!-- <input-grid
              v-model="formData['PROD_INST-100010096'].text"
              sqlCode="findCust"
              @getrow="
                (val) => {
                  formData['PROD_INST-100010096'].value = val;
                }
              "
            /> -->
            <input-dialog
              v-model="formData['PROD_INST-100010096'].text"
              text="custName"
              @getrow="getrowHandler"
              @input="searchInfo"
              @loadata="loadBusiManageOptions"
              :config="busiManageConfig"
            />
          </el-form-item>
          <el-form-item label="省付费账户" :required="accReq">
            <add-amount
              :infors="infors"
              @getrow="getAccInfo"
              @getAccData="getAccData"
            ></add-amount>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import config from "./config";
import OrderService from "@/api/order/OrderService.js";
// import loadMixins from "@/mixins/order/prodevent.js";
import inputDialog from "@/components/public/forms/inputDialog";
import addAmount from "./addAmount.vue";
import { deepClone } from "../../utils/clone";
let ApplyNum = function (rule, value, callback) {
  if (value < 1 || value > 200) {
    callback(new Error("请输入[1,200]之间的数字"));
  } else {
    callback();
  }
};

let completeTime = function(rule, value,callback){
    let nowDate = new Date();
    let year = nowDate.getFullYear();
    let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    let dateStr = year + "-" + month + "-" + day+" 00:00:00";
    const now = new Date(dateStr).getTime()
    let valueS = value+" 00:00:00";
    const _value = new Date(valueS).getTime()
    if (_value < now ) {
        callback(new Error('完成时间必须大于当前时间'));
    } else {
        callback();
    }
}

export default {
  name: "OrderitemInfo",
  // mixins: [loadMixins],
  created() {
    Object.assign(this.formData, this.config);
  },
  props: {
    infors: {
      type: Object,
      default() {
        return {
          custSoNumber: "",
        };
      },
    },
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  components: {
    inputDialog,
    addAmount,
  },
  data() {
    return {
      config: deepClone(config),
      hireTime: "",
      hireUnit: "年",
      fm: {
        hireTime: "",
      },
      formDataRules: {
        "104324520.value": [
          { required: true, message: "申请数量必填", trigger: "blur" },
          { type: "number", message: "申请数量必须为数字值", trigger: "blur" },
          { validator: ApplyNum, trigger: "blur" },
        ],
        "ORDER_ITEM-ORDER_DATE.value": [
          { required: true, message: "要求完成时间必填", trigger: "change" },
          { validator: completeTime, trigger: "change" },
        ],
        "TD_V_PROD_INST-100010097.value": [
          { required: true, message: "集团付费账户必填", trigger: ["change","blur"]},
        ],
        'PROD_INST-100010096.value':[
           { required: true, message: "付费运营商必填", trigger: ["change","blur"] },
        ]
      },
      rules: {
        hireTime: [
          { required: true, message: "租用期限必填", trigger: "blur" },
          { type: "number", message: "租用期限必须为数字值", trigger: "blur" },
        ],
      },
      operators: "", //付费运营商
      //集团付费账户
      busiManageConfig1: {
        title: "集团付费账户",
        tableData: [],
        tableForm: {
          items: [
            {
              field: "acctNumber",
              title: "账户编码",
              itemRender: {
                name: "input",
                attrs: { placeholder: "请输入关键字" },
              },
            },
            {
              field: "acctName",
              title: "账户名称",
              itemRender: {
                name: "input",
                attrs: { placeholder: "请输入关键字" },
              },
            },
            {
              itemRender: {
                name: "$button",
                props: { content: "查询", type: "submit", status: "primary" },
              },
            },
          ],
          data: {}, //这个data一定要加，否则无法获取查询参数
        },
        tableColumn: [
          { field: "acctNumber", title: "账户编码", width: "20%" },
          // { field: "provinceAccountNumber", title: "省账户编码", width: "20%" },
          { field: "acctName", title: "账户名称", width: "20%" },
          // { field: "provinceAccountId", title: "省账户ID", width: "20%" },
          // { field: "provinceName", title: "省", width: "20%" },
          // { field: "lanName", title: "本地网", width: "20%" },
        ],
      },
      //付费运营商
      busiManageConfig: {
        title: "付费运营商",
        tableData: [],
        tableForm: {
          items: [
            {
              field: "staffName",
              title: "运营商/代理商",
              itemRender: {
                name: "input",
                attrs: { placeholder: "请输入关键字" },
              },
            },
            {
              field: "staffCode",
              title: "运营商/代理商编码",
              itemRender: {
                name: "input",
                attrs: { placeholder: "请输入关键字" },
              },
            },
            {
              itemRender: {
                name: "$button",
                props: { content: "查询", type: "submit", status: "primary" },
              },
            },
          ],
          data: {}, //这个data一定要加，否则无法获取查询参数
        },
        tableColumn: [
          { field: "oldPartyCode", title: "运营商/代理商编码", width: "33.3%" },
          { field: "custName", title: "运营商/代理商", width: "33.3%" },
          { field: "custAddr", title: "运营商/代理商地址", width: "33.3%" },
        ],
      },
      //要求完成日期限制
      taxStartDate: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1;
        },
      },
      userInfo: {}, //登录人信息
      disabled: false,
      accReq: false, //省账户必填标识
    };
  },
  mounted() {
    sessionStorage.removeItem("citySelectA");
    sessionStorage.removeItem("citySelectB"); //清除城市选择缓存，防止有些产品没有城市选择拦截问题
    let FormModel = JSON.parse(sessionStorage.getItem("FormModel"));
    this.userInfo = JSON.parse(sessionStorage.getItem("crm3-userinfo"));
    if (FormModel.orderstage == "50030003") {
      this.formData["ORDER_ITEM-REQ_TYPE"].value = "80050034001";
    } else {
      this.formData["ORDER_ITEM-REQ_TYPE"].value = "80050034002";
    }
    if (FormModel.orderDate != undefined && FormModel.orderDate != "") {
      this.formData["ORDER_ITEM-ORDER_DATE"].value = FormModel.orderDate;
      // let gtOrgId = [
      //   "442",
      //   "1944889",
      //   "1944890",
      //   "1944891",
      //   "1950850",
      //   "1978013",
      // ];
      // if (
      //   gtOrgId.indexOf(this.userInfo.orgId) != -1 ||
      //   this.userInfo.departmentId == 1947362
      // ) {
      //   this.disabled = true;
      // }
    } //要求完成时间，商机单是会带过来，带宽型可以修改，非带宽型不可修改（暂时只有带宽型暂不判断）
    this.defaultInfo();
    this.getTestProvCount();
  },
  methods: {
    //初始获取默认账户事件
    defaultInfo() {
      let params2 = {
        interFaceType: "CUST",
        sqlId: 2021042901,
        paramStr:
          "custId:" +
          this.infors.custId +
          ";" +
          "regionId:" +
          this.userInfo.regionId +
          ";" +
          "regionType:" +
          this.userInfo.regionType,
      };
      this.getCustNum(params2); //客户默认账号
    },
    //查询省账户是否必填
    async getTestProvCount() {
      let reault = await OrderService.getTestProvCount({
        regionId: this.userInfo.regionId,
        regionCode: this.userInfo.regionCode,
        regionType: this.userInfo.regionType,
        flagType: "ACCT",
      });
      if (reault.code == 200) {
        if (reault.meta.count != 0) {
          this.accReq = true;
        }
        sessionStorage.setItem("accReq", this.accReq);
      }
    },
    /**
     * 组装传入的参数到paramModel
     */
    async getCustNum(params) {
      //客户默认账号  20210830 付费客户从客户定位带回，付费账户从接口取值 
      this.formData["PROD_INST-100010096"].text = this.infors.custName;
      this.formData["PROD_INST-100010096"].value = this.infors.custId;
      const result = await OrderService.getCustNum(params);
      if (result.code == 200) {
        this.formData["TD_V_PROD_INST-100010097"].text =
          result.meta.resList.executeSqlResp[0].acctName;

        this.formData["TD_V_PROD_INST-100010097"].value =
          result.meta.resList.executeSqlResp[0].acctId;
      }
    },
    assemble() {
      this.formData["ORDER_ITEM-CUST_SO_NUMBER"].value =
        this.infors["custSoNumber"];
      // 关联租用性质的时间设置
      this.formData[
        "DISP_HIRE_TIME"
      ].value = `${this.hireTime}${this.hireUnit}`;
    },
    onHireTime() {
      this.formData[
        "DISP_HIRE_TIME"
      ].value = `${this.hireTime}${this.hireUnit}`;
      this.fm.hireTime = this.hireTime;
    },
    //付费账户查询事件
    async loadBusiManageOptions2(val) {
      let acctNumber = val.acctNumber ? val.acctNumber : "";
      let acctName = val.acctName ? val.acctName : "";
      let custId = this.infors.custId ? this.infors.custId : ''
      let params = {
        interFaceType: "CUST",
        sqlId: 2021042902,
        paramStr:
          "custId:" + 
          custId +
          ";acctNumber:" +
          acctNumber +
          ";acctName:" +
          acctName,
      };
      let result = await this.getCustAcct(params);
      if (result.code == 200) {
        this.busiManageConfig1.tableData = result.meta.resList.executeSqlResp;
      }
    },
    //付费运营商查询事件
    async loadBusiManageOptions(val) {
      let oldPartyCode = val.staffCode ? val.staffCode : "";
      let custName = val.staffName ? val.staffName : "";
      let params = {
        interFaceType: "CUST",
        sqlId: 2021042903,
        paramStr:
          "custId:" +
          this.infors.custId +
          ";oldPartyCode:" +
          oldPartyCode +
          ";custName:" +
          custName,
      };
      let result = await this.getCustAcct(params);
      if (result.code == 200) {
        this.busiManageConfig.tableData = result.meta.resList.executeSqlResp;
      }
    },
    //付费账户列表/付费运营商/选择用户
    async getCustAcct(params) {
      const result = await OrderService.getCustNum(params);
      return result;
    },
    //付费账户选中行
    getrowHandler2(value) {
      //付费账户选中行事件
      let accountId = value.accountId;
      this.formData["TD_V_PROD_INST-100010097"].value = accountId;
    },
    async getrowHandler(value) {
      //付费运营商选中行事件
      let accountId = value.custId;
      this.formData["PROD_INST-100010096"].value = accountId;
      let params = {
        interFaceType: "CUST",
        sqlId: 2021042901,
        paramStr: "custId:" + accountId,
      };
      const result = await OrderService.getCustNum(params);
      if (result.code == 200) {
        if (result.meta.resList.executeSqlResp.length > 0) {
          this.formData["TD_V_PROD_INST-100010097"].text =
            result.meta.resList.executeSqlResp[0].acctName;
          this.formData["TD_V_PROD_INST-100010097"].value =
            result.meta.resList.executeSqlResp[0].acctId;
        }
      }
    },
    //查询事件
    async searchInfo() {},
    //付费方式切换
    selectA() {
      let value = this.formData["PROD_INST-100010204"].value;
      if (value == 30010002) {
        //付费运营商
        this.formData["PROD_INST-100010096"].value = "";
        this.formData["PROD_INST-100010096"].text = "";
        this.formData["TD_V_PROD_INST-100010097"].value = "";
        this.formData["TD_V_PROD_INST-100010097"].text = "";
        this.$nextTick(()=>{
          this.$refs.formDataRules.clearValidate(['TD_V_PROD_INST-100010097.value','PROD_INST-100010096.value']);
        })
      } else if (value == 30010001) {
        //客户付费
        this.defaultInfo();
      }
    },
    //选中省账户
    getAccInfo(row) {
      this.formData["PROD_INST-142003019"].value = row.PROVINCE_ACCOUNT_ID
        ? row.PROVINCE_ACCOUNT_ID
        : "";
      this.formData["PROD_INST-142003020"].value = row.PROVINCE_ACCOUNT_NUMBER
        ? row.PROVINCE_ACCOUNT_NUMBER
        : "";
    },
    getAccData(val) {
      this.formData["PROD_INST-142003019"].value = val.province_account_id
        ? val.province_account_id
        : "";
      this.formData["PROD_INST-142003020"].value = val.province_account_number
        ? val.province_account_number
        : "";
      this.formData["TD_V_PROD_INST-100010097"].text =
        val.resultObject.acctName;
      this.formData["TD_V_PROD_INST-100010097"].value = val.resultObject.acctId;
    },
    //租用性质切换
    selectRent() {
      this.hireTime = "";
      this.formData["DISP_HIRE_TIME"].value = "";
    },
    validateAll() {
      let res1 = false,
        res2 = false;
      this.$refs["formDataRules"].validate((valid) => {
        res1 = valid;
      });
      this.$refs["fm"].validate((valid) => {
        res2 = valid;
      });
      return res1 && res2;
    },
  },
};
</script>

<style>
</style>
